package com.hxzy.tms.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.hxzy.tms.dao.HibernateBaseDao;
import com.hxzy.tms.dao.UserDao;
import com.hxzy.tms.entity.User;

public class DefaultUserDao extends HibernateBaseDao<User> implements UserDao {
    private Logger logger = LoggerFactory.getLogger(getClass());
    // private Session session;

    public User load(long id) {
        // Session session = HibernateSessionHolder.get();
        return (User) getSession().load(User.class, id);
    }

    @SuppressWarnings("deprecation")
    public User find(long id) {
        // Session session = HibernateSessionHolder.get();
        return (User) getSession().get(User.class, id);
    }

    public User get(final String username) {
        // Session session = HibernateSessionHolder.get();
        Query query = getSession().createQuery("from User where username = :username");
        query.setString("username", username);
        @SuppressWarnings("unchecked")
        List<User> userList = query.list();
        if (userList == null || userList.isEmpty()) {
            return null;
        }
        if (userList.size() > 1) {
            logger.error("数据异常：到多个用户名为 {} 的用户。", username);
        }
        return userList.get(0);
    }

    public void saveOrUpdate(User user) {
        // Session session = HibernateSessionHolder.get();
        getSession().saveOrUpdate(user);
    }

}
